# -*- coding: utf-8 -*-
"""
TG Trader Tools 主窗口组件
"""
from PySide6.QtWidgets import QMainWindow, QWidget
from PySide6.QtCore import Qt

from ..base import TgComponentMixin
from ..layouts import TgSplitterLayout
from .menu_area import TgMenuArea
from .content_area import TgContentArea
from ...plugin_manager import PluginManager


class TgMainWindow(QMainWindow, TgComponentMixin):
    """TG主窗口组件"""
    
    def __init__(self, custom_plugins=None, show_demo_plugins=True):
        # 初始化TG组件属性
        self._component_name = self.__class__.__name__
        self._is_initialized = False
        self._style_applied = False
        self._theme = 'default'
        self._size_hint = 'medium'
        
        # 先初始化父类
        QMainWindow.__init__(self)
        TgComponentMixin.__init__(self)
        
        # 创建插件管理器
        self.plugin_manager = PluginManager()
        
        # 手动调用初始化
        self.initialize()
        
        # 设置连接和加载插件
        self.setup_connections()
        self.load_plugins(custom_plugins=custom_plugins, show_demo_plugins=show_demo_plugins)
    
    def setup_ui(self):
        """设置用户界面"""
        self.setWindowTitle("TG Trader Tools")
        self.setMinimumSize(1200, 800)
        
        # 创建主布局（分割器布局）
        self.main_layout = TgSplitterLayout(Qt.Orientation.Horizontal)
        self.setCentralWidget(self.main_layout)
        
        # 创建菜单区域
        self.menu_area = TgMenuArea("功能菜单")
        self.main_layout.add_widget(self.menu_area)
        
        # 创建内容区域
        self.content_area = TgContentArea()
        self.main_layout.add_widget(self.content_area)
        
        # 设置分割器比例
        self.main_layout.set_sizes([250, 950])
        self.main_layout.set_children_collapsible(False)
    
    def apply_style(self):
        """应用样式"""
        # 主窗口的样式通过其子组件来实现
        self._style_applied = True
    
    def setup_connections(self):
        """设置信号连接"""
        self.menu_area.menu_item_clicked.connect(self.on_menu_item_clicked)
    
    def load_plugins(self, custom_plugins=None, show_demo_plugins=True):
        """加载插件"""
        # 加载默认插件
        self.plugin_manager.load_plugins(load_defaults=show_demo_plugins)
        
        # 加载自定义插件
        if custom_plugins:
            for plugin in custom_plugins:
                self.plugin_manager.add_plugin(plugin)
        
        # 将所有插件添加到菜单
        for plugin in self.plugin_manager.get_plugins():
            self.add_plugin_to_menu(plugin)
    
    def add_plugin_to_menu(self, plugin):
        """添加插件到菜单"""
        # 添加菜单项
        self.menu_area.add_menu_item(plugin.get_name(), plugin)
        
        # 将插件界面添加到内容区域
        plugin_widget = plugin.get_widget()
        self.content_area.add_content_widget(plugin_widget)
        
        # 存储插件和其界面的映射关系
        if not hasattr(self, '_plugin_widgets'):
            self._plugin_widgets = {}
        self._plugin_widgets[plugin] = plugin_widget
    
    def on_menu_item_clicked(self, data):
        """菜单项点击事件处理"""
        if hasattr(data, 'get_widget'):  # 检查是否是插件对象
            # 处理插件点击
            self.show_plugin_page(data)
        else:
            raise Exception(f"must have get_widget attribute")
    
    def show_plugin_page(self, plugin):
        """显示插件页面"""
        # 设置标题
        self.content_area.set_title(plugin.get_name())
        # 获取已经添加到内容区域的插件界面
        if hasattr(self, '_plugin_widgets') and plugin in self._plugin_widgets:
            plugin_widget = self._plugin_widgets[plugin]
            # 显示插件界面
            self.content_area.set_current_widget(plugin_widget)
    
    def closeEvent(self, event):
        """窗口关闭事件处理"""
        # 清理所有插件资源
        if hasattr(self, 'plugin_manager'):
            self.plugin_manager.unload_all_plugins()
        
        # 调用父类的关闭事件
        super().closeEvent(event)
    